package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import static com.sky.constant.MessageConstant.LOGIN_FAILED;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private WeChatProperties properties;

    @Autowired
    private UserMapper userMapper;
    //微信服务接口地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Override
    public User login(UserLoginDTO userLoginDTO) {

        String openid = getString(userLoginDTO);

        //如果openid是空的，为不合法请求
        if (openid == null) {
            throw new LoginFailedException(LOGIN_FAILED);
        }
        User user = userMapper.queryByOpenid(openid);
        //如果数据库中没有，新建用户
        if (Objects.isNull(user)) {
            User newUser = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(newUser);
        }
        return user;
    }

    /**
     * 获取openid
     *
     * @param
     * @return
     */
    private String getString(UserLoginDTO userLoginDTO) {
        Map<String, String> map = new HashMap<>();
        map.put("secret", properties.getSecret());
        map.put("appid", properties.getAppid());
        map.put("js_code", userLoginDTO.getCode());
        map.put("grant_type", "authorization_code");

        //调用接口服务，提取openId
        String json = HttpClientUtil.doGet(WX_LOGIN, map);
        //序列化为对象
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");

        return openid;
    }
}
